package com.neolix.watch.BroadcastReceiver;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.neolix.watch.NeolixApplication;
import com.neolix.watch.bluetooth.BlueToothUtil;
import com.neolix.watch.domain.NotificationType;
import com.neolix.watch.util.CommonHelper;
import com.neolix.watch.util.SharedPreferencesUtil;
import com.neolix.watch.util.StringUtil;

import static com.neolix.watch.util.StringUtil.isNotBlank;

public class PhoneReceiver extends BroadcastReceiver {
    private String TAG = PhoneReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "来电");
        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            //如果是去电（拨出）
            Log.i(TAG, "拨出");
        } else {
            //查了下android文档，貌似没有专门用于接收来电的action,所以，非去电即来电
            Log.d(TAG, "来电");
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    PhoneStateListener listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            //state 当前状态 incomingNumber,貌似没有去电的API
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    Log.d(TAG, "挂断");
                    if(SharedPreferencesUtil.isSendInComingInfo()) {
                        //TODO 通知手表
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Log.d(TAG, "接听");
                    if(SharedPreferencesUtil.isSendInComingInfo()) {
                        //TODO 通知手表
                    }
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Log.d(TAG, "响铃:来电号码" + incomingNumber);
                    //TODO 通知手表
                    if(SharedPreferencesUtil.isSendInComingInfo()) {
                        String number = CommonHelper.getContactNameByPhoneNumber(NeolixApplication.getInstance(), incomingNumber);
                        BlueToothUtil.syncNotification(NotificationType.TELPHONE, isNotBlank(number) ? number : incomingNumber, "");
                    }
                    break;
            }
        }
    };
}